package com.cupk.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class COSUtil {
    /**
     * 腾讯云COS
     * SecretId:AKIDGa===============uqeHiw
     * SecretKey:CHCC===========8GLM
     */
    public static String SECRET_ID = "AKIDVsuhGahdKmy72h7XiibK821tcBczGRpA";
    public static String SECRET_KEY = "ISbgfWEWpswvIVWN7mOo05zqW0EEzpTy";
    public static String BUCKET_NAME = "cupk-1324569366";
    public static String REGION = "ap-beijing";
    public static String prePath = "CUPKCSEI/"; //期望的存的前缀
    /**
     * 获取客户端对象
     *
     * @return
     */
    public static COSClient getInstance() {
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        Region region = new Region(REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cred, clientConfig);
    }

    /**
     * 图片上传
     *
     * @param in
     * @param ext
     * @param contentType
     * @return
     */
    public static String upLoad(InputStream in, String ext, String contentType) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        String key = prePath + getTimeStamp() + ext;
        objectMetadata.setContentType(contentType);
        PutObjectResult putObjectResult = getInstance().putObject(BUCKET_NAME, key, in, objectMetadata);
        return "http://" + BUCKET_NAME + ".cos." + REGION + ".myqcloud.com/" + key; //返回上传的图片的地址
    }

    // 获得时间戳
    public static String getTimeStamp() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
        return dateTime;
    }

}